<template>
  <Layout>
    <NavBar :isShowLeftIcon="false" :iconName="``" :navTitle="`记账统计`"/>
    <div v-if="recordList.length>0">
      <Charts :options="polar"/>
      <Tabs class-prefix="type" :data-source="recordTypeList" :value.sync="recordType"/>
      <ol>
        <li v-for="(group,index) in records" :key="index">
          <h3 class="title">{{ beautify(group.title) }}<span>￥{{ group.total }}</span></h3>
          <ol>
            <li v-for="item in group.items" :key="item.id"
                class="record">
              <span>{{ tagToString(item.tags) }}</span>
              <span class="notes">{{ item.notes }}</span>
              <span>￥{{ item.amount }}</span>
            </li>
          </ol>
        </li>
      </ol>
    </div>
    <div v-else>
      暂无记录
    </div>
  </Layout>
</template>

<script lang="ts">
import Vue from 'vue';
import {Component} from 'vue-property-decorator';
import Tabs from '@/components/Common/Tabs.vue';
import recordTypeList from '@/constants/recordTypeList';
import dayjs from 'dayjs';
import clone from '@/lib/clone';
import 'echarts/lib/chart/line';
import 'echarts/lib/component/polar';
import Charts from '@/components/Common/Charts.vue';
import tag from '@/store/modules/tag';

@Component({
  components: {Tabs, Charts},
})
export default class Statistics extends Vue {
  recordTypeList = recordTypeList;
  recordType = '-';

  get recordList() {
    return this.$store.state.recordList;
  }

  get polar() {
    const value = window.localStorage.getItem('recordList');
    const data = JSON.parse(value && value !== 'undefined' ? value : '[]');
    const category: string[] = [];
    const incomeData: number[] = [];
    const expenditureData: number[] = [];
    const newRecordList = clone(data).sort((a: RecordItem, b: RecordItem) => dayjs(a.createdAt).valueOf() - dayjs(b.createdAt).valueOf());
    const result: { title: string; incomeTotal: number; expenditureTotal: number }[] = [];
    for (let i = 0; i < newRecordList.length; i++) {
      const index = result.findIndex((item) => {
        return dayjs(item.title).isSame(dayjs(newRecordList[i].createdAt), 'day');
      });
      if (index >= 0) {
        if (newRecordList[i].type === '+') {
          result[index].incomeTotal += parseFloat(newRecordList[i].amount);
        } else if (newRecordList[i].type === '-') {
          result[index].expenditureTotal += parseFloat(newRecordList[i].amount);
        }
      } else {
        result.push({
          title: newRecordList[i].createdAt,
          incomeTotal: newRecordList[i].type === '+' ? parseFloat(newRecordList[i].amount) : 0,
          expenditureTotal: newRecordList[i].type === '-' ? parseFloat(newRecordList[i].amount) : 0
        });
      }
    }
    result.map(group => {
      category.push(this.beautify(group.title, true));
      incomeData.push(group.incomeTotal);
      expenditureData.push(group.expenditureTotal);
    });
    return {
      title: {
        text: '收支统计'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['收入', '支出']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: category
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '支出',
          type: 'line',
          stack: '总量',
          data: expenditureData
        },
        {
          name: '收入',
          type: 'line',
          stack: '总量',
          data: incomeData
        },
      ]
    };
  }

  get records() {
    if (this.recordList.length === 0) return [];
    const newRecordList = clone(this.recordList).filter((item: RecordItem) => item.type === this.recordType)
        .sort((a: RecordItem, b: RecordItem) => dayjs(b.createdAt).valueOf() - dayjs(a.createdAt).valueOf());
    const result: { title: string; total: number; items: RecordItem[] }[] = [];
    for (let i = 0; i < newRecordList.length; i++) {
      const index = result.findIndex(item => dayjs(item.title).isSame(dayjs(newRecordList[i].createdAt), 'day'));
      if (index >= 0) {
        result[index].items.push(newRecordList[i]);
      } else {
        result.push({title: newRecordList[i].createdAt, total: newRecordList[i].amount, items: [newRecordList[i]]});
      }
    }
    result.slice(0, 30).map(group => {
      group.total = group.items.reduce((sum, item) => sum + parseFloat(item.amount), 0);
    });
    return result;
  }

  created() {
    this.$store.dispatch('getRecordList');
  }

  tagToString(tags: Tag[]) {
    return tags.length > 0 ? tags.join(',') : '无';
  }

  beautify(timeString: string, flag = false) {
    const day = dayjs(timeString);
    const now = dayjs();
    if (day.isSame(now, 'day')) {
      return '今天';
    } else if (day.isSame(now.subtract(1, 'day'), 'day')) {
      return '昨天';
    } else if (day.isSame(now.subtract(2, 'day'), 'day')) {
      return '前天';
    } else if (day.isSame(now, 'year')) {
      return flag ? day.format('MM/DD') : day.format('M月D日');
    } else {
      return day.format('YYYY年M月D日');
    }
  }

}
</script>

<style lang="scss" scoped>
.echarts {
  width: 100%;
  //height: 100%;
}

::v-deep li.interval-item {
  height: 44px;
  font-size: 18px;
}

%item {
  padding: 0 16px;
  min-height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  @extend %item;
}

.record {
  @extend %item;
  background-color: white;
  position: relative;

  > .notes {
    margin-right: auto;
    margin-left: 8px;
    color: #999999;
  }
}

.record::before {
  content: '';
  border-bottom: #f5f5f5 solid 1px;
  width: 95%;
  position: absolute;
  bottom: 0;
}
</style>
